package org.oims.simpleserver.filters;


import org.apache.commons.lang3.StringUtils;
import org.oims.simpleserver.entities.results.ErrorResult;
import org.oims.simpleserver.utils.ReturnResultUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

public class AuthenticateFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        //如果不能从session中找到用户对象属性
        if(user == null){
            String url = req.getRequestURI();
            //如果是登登录操作，放行
            if(StringUtils.equals(url, "/api/v1/login")){
                filterChain.doFilter(servletRequest, servletResponse);
            }else {
                //拦截，并提示需要登录
                ErrorResult res = ReturnResultUtil.getErrorResult(1, "Please login.");
                HttpServletResponse resp = (HttpServletResponse) servletResponse;
//                resp.setStatus(406);
                resp.setContentType("application/json; charset=utf-8");
                PrintWriter pt = resp.getWriter();
                pt.print(res.toString());
                pt.flush();
            }
        }else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
